import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader } from '../components/UI/Card';
import { Badge } from '../components/UI/Badge';
import { Button } from '../components/UI/Button';
import { Modal } from '../components/UI/Modal';
import { ConfirmDialog } from '../components/UI/ConfirmDialog';
import { ToastContainer } from '../components/UI/Toast';
import { Pagination } from '../components/UI/Pagination';
import { useToast } from '../hooks/useToast';
import { mockApi } from '../services/mockApi';
import { api } from '../services/api';
import { Cargo } from '../types';
import { 
  Plus,
  Search,
  Edit,
  Trash2,
  Package,
  Save,
  X,
  Calendar,
  Tag,
  Ruler,
  Hash,
  Eye,
  Box,
  FileText,
  RotateCcw,
  Filter
} from 'lucide-react';

interface CargoForm {
  name: string;
  specification: string;
  unit: string;
}

interface SearchFilters {
  productName: string;
  specification: string;
  skuCode: string;
}

export const CargoPage: React.FC = () => {
  const [cargos, setCargos] = useState<Cargo[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCargo, setSelectedCargo] = useState<Cargo | null>(null);
  const [editingCargo, setEditingCargo] = useState<Cargo | null>(null);
  const [deletingCargo, setDeletingCargo] = useState<Cargo | null>(null);
  
  // 模态框状态
  const [showCargoModal, setShowCargoModal] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  
  // 搜索状态
  const [searchFilters, setSearchFilters] = useState<SearchFilters>({
    productName: '',
    specification: '',
    skuCode: ''
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalCargos, setTotalCargos] = useState(0);
  
  // 表单状态
  const [cargoForm, setCargoForm] = useState<CargoForm>({
    name: '',
    specification: '',
    unit: '卷'
  });
  
  const [createLoading, setCreateLoading] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [searchLoading, setSearchLoading] = useState(false);

  const { toasts, removeToast, success, error } = useToast();

  const pageSize = 10;

  // 初始加载数据
  useEffect(() => {
    fetchCargos();
  }, [currentPage]);

  const fetchCargos = async (searchParams?: SearchFilters) => {
    try {
      setLoading(true);
      const params = searchParams || searchFilters;
      const result = await api.cargo.getCargos({
        page: currentPage,
        limit: pageSize,
        productName: params.productName || undefined,
        specification: params.specification || undefined,
        skuCode: params.skuCode || undefined,
      });
      setCargos(result.data);
      setTotalCargos(result.total);
    } catch (err) {
      console.error('获取货物列表失败:', err);
      error('获取货物列表失败', err instanceof Error ? err.message : '获取货物列表失败');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setCargoForm({
      name: '',
      specification: '',
      unit: '卷'
    });
  };

  const handleCreateCargo = async () => {
    try {
      setCreateLoading(true);

      if (!cargoForm.name.trim()) {
        error('表单验证失败', '请输入货物名称');
        return;
      }

      if (!cargoForm.unit.trim()) {
        error('表单验证失败', '请输入计量单位');
        return;
      }

      const newCargo = {
        name: cargoForm.name.trim(),
        specification: cargoForm.specification.trim(),
        unit: cargoForm.unit.trim(),
      };

      await api.cargo.createCargo(newCargo);

      success('货物创建成功', '新货物已成功创建');
      resetForm();
      setShowCreateModal(false);
      await fetchCargos();

    } catch (err) {
      console.error('创建货物失败:', err);
      error('创建货物失败', err instanceof Error ? err.message : '创建货物失败');
    } finally {
      setCreateLoading(false);
    }
  };

  const handleEditCargo = (cargo: Cargo) => {
    setEditingCargo(cargo);
    setCargoForm({
      name: cargo.name,
      specification: cargo.specification || '',
      unit: cargo.unit
    });
    setShowEditModal(true);
  };

  const handleSaveEdit = async () => {
    if (!editingCargo) return;

    try {
      setEditLoading(true);

      if (!cargoForm.name.trim()) {
        error('表单验证失败', '请输入货物名称');
        return;
      }

      if (!cargoForm.unit.trim()) {
        error('表单验证失败', '请输入计量单位');
        return;
      }

      const updates = {
        name: cargoForm.name.trim(),
        specification: cargoForm.specification.trim(),
        unit: cargoForm.unit.trim(),
      };

      await api.cargo.updateCargo(editingCargo.id, updates);

      success('货物更新成功', '货物信息已成功更新');
      resetForm();
      setEditingCargo(null);
      setShowEditModal(false);
      await fetchCargos();

    } catch (err) {
      console.error('更新货物失败:', err);
      error('更新货物失败', err instanceof Error ? err.message : '更新货物失败');
    } finally {
      setEditLoading(false);
    }
  };

  const handleDeleteCargo = (cargo: Cargo) => {
    setDeletingCargo(cargo);
    setShowDeleteDialog(true);
  };

  const confirmDelete = async () => {
    if (!deletingCargo) return;

    try {
      setDeleteLoading(true);
      
      const result = await api.cargo.deleteCargo(deletingCargo.id);
      
      if (result) {
        success('货物删除成功', `货物 ${deletingCargo.name} 已成功删除`);
        await fetchCargos();
      } else {
        error('删除失败', '删除货物失败');
      }
    } catch (err) {
      console.error('删除货物失败:', err);
      error('删除失败', err instanceof Error ? err.message : '删除货物失败');
    } finally {
      setDeleteLoading(false);
      setDeletingCargo(null);
      setShowDeleteDialog(false);
    }
  };

  const handleViewCargo = (cargo: Cargo) => {
    setSelectedCargo(cargo);
    setShowCargoModal(true);
  };

  // 处理搜索输入变化（不触发请求）
  const handleSearchChange = (field: keyof SearchFilters, value: string) => {
    setSearchFilters(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 执行搜索
  const handleSearch = async () => {
    try {
      setSearchLoading(true);
      setCurrentPage(1); // 重置到第一页
      await fetchCargos(searchFilters);
    } finally {
      setSearchLoading(false);
    }
  };

  // 清空搜索并重新获取数据
  const clearSearch = async () => {
    const emptyFilters = {
      productName: '',
      specification: '',
      skuCode: ''
    };
    setSearchFilters(emptyFilters);
    setCurrentPage(1);
    await fetchCargos(emptyFilters);
  };

  // 检查是否有搜索条件
  const hasSearchFilters = Object.values(searchFilters).some(value => value.trim() !== '');

  const totalPages = Math.ceil(totalCargos / pageSize);

  return (
    <div className="space-y-6 animate-slide-up">
      {/* Toast 通知容器 */}
      <ToastContainer toasts={toasts} onClose={removeToast} />

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">货物管理</h1>
          <p className="text-gray-600">管理所有货物的信息和库存</p>
        </div>
        <Button onClick={() => setShowCreateModal(true)} icon={<Plus className="w-4 h-4" />}>
          新增货物
        </Button>
      </div>

      {/* 搜索筛选器 */}
      <Card>
        <CardContent className="p-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-medium text-gray-800">搜索筛选</h3>
              <div className="flex items-center space-x-2">
                {hasSearchFilters && (
                  <Button
                    variant="ghost"
                    size="sm"
                    icon={<X className="w-4 h-4" />}
                    onClick={clearSearch}
                    className="text-gray-500 hover:text-gray-700"
                  >
                    清空
                  </Button>
                )}
                <Button
                  variant="outline"
                  size="sm"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleSearch}
                  loading={searchLoading}
                  className="text-primary-600 border-primary-200 hover:bg-primary-50"
                >
                  搜索
                </Button>
              </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* 货物名称搜索 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  货物名称
                </label>
                <div className="relative">
                  <Box className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <input
                    type="text"
                    placeholder="输入货物名称..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                    value={searchFilters.productName}
                    onChange={(e) => handleSearchChange('productName', e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                </div>
              </div>

              {/* 规格搜索 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  规格
                </label>
                <div className="relative">
                  <FileText className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <input
                    type="text"
                    placeholder="输入规格..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                    value={searchFilters.specification}
                    onChange={(e) => handleSearchChange('specification', e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                </div>
              </div>

              {/* SKU编码搜索 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  SKU编码
                </label>
                <div className="relative">
                  <Hash className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <input
                    type="text"
                    placeholder="输入SKU编码..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                    value={searchFilters.skuCode}
                    onChange={(e) => handleSearchChange('skuCode', e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 货物列表 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-800">货物列表</h2>
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-500">共 {totalCargos} 个货物</span>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-6">
              <div className="space-y-4">
                {Array.from({ length: 5 }).map((_, i) => (
                  <div key={i} className="flex items-center space-x-4 animate-pulse">
                    <div className="w-16 h-16 bg-gray-200 rounded-xl"></div>
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-gray-200 rounded w-1/4"></div>
                      <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <>
              <div className="divide-y divide-gray-100">
                {cargos.map((cargo) => (
                  <div 
                    key={cargo.id} 
                    className="p-6 hover:bg-gray-50 transition-colors duration-200 cursor-pointer"
                    onClick={() => handleViewCargo(cargo)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4">
                        <div className="w-12 h-12 bg-gradient-to-br from-primary-100 to-secondary-100 rounded-xl flex items-center justify-center">
                          <Box className="w-6 h-6 text-primary-600" />
                        </div>
                        <div>
                          <div className="flex items-center space-x-2 mb-1">
                            <h3 className="font-semibold text-gray-800">{cargo.name}</h3>
                            <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                              {cargo.unit}
                            </span>
                          </div>
                          <div className="flex items-center space-x-4 text-sm text-gray-600">
                            <div className="flex items-center space-x-1">
                              <Hash className="w-4 h-4" />
                              <span>SKU: {cargo.id}</span>
                            </div>
                            {cargo.specification && (
                              <div className="flex items-center space-x-1">
                                <FileText className="w-4 h-4" />
                                <span>规格: {cargo.specification}</span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          icon={<Eye className="w-4 h-4" />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleViewCargo(cargo);
                          }}
                        >
                          查看
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          icon={<Edit className="w-4 h-4" />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleEditCargo(cargo);
                          }}
                        >
                          编辑
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          icon={<Trash2 className="w-4 h-4" />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDeleteCargo(cargo);
                          }}
                          className="text-error-600 hover:text-error-700 hover:bg-error-50"
                        >
                          删除
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* 分页 */}
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalCargos}
                onPageChange={setCurrentPage}
                className="p-6 border-t border-gray-100"
              />
            </>
          )}
        </CardContent>
      </Card>

      {/* 货物详情模态框 */}
      <Modal
        isOpen={showCargoModal}
        onClose={() => setShowCargoModal(false)}
        title="货物详情"
        size="md"
      >
        {selectedCargo && (
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="text-sm font-medium text-gray-600">货物名称</label>
                <p className="text-lg font-semibold text-gray-800">{selectedCargo.name}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600">SKU编码</label>
                <p className="text-lg font-semibold text-gray-800">{selectedCargo.id}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600">规格</label>
                <p className="text-lg font-semibold text-gray-800">
                  {selectedCargo.specification || '无'}
                </p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600">计量单位</label>
                <p className="text-lg font-semibold text-gray-800">{selectedCargo.unit}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600">创建时间</label>
                <p className="text-gray-800">{selectedCargo.createdAt}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600">更新时间</label>
                <p className="text-gray-800">{selectedCargo.updatedAt}</p>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* 新增货物模态框 */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false);
          resetForm();
        }}
        title="新增货物"
        size="md"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              货物名称 <span className="text-error-500">*</span>
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={cargoForm.name}
              onChange={(e) => setCargoForm(prev => ({ ...prev, name: e.target.value }))}
              placeholder="请输入货物名称"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              规格
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={cargoForm.specification}
              onChange={(e) => setCargoForm(prev => ({ ...prev, specification: e.target.value }))}
              placeholder="请输入规格"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              计量单位 <span className="text-error-500">*</span>
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={cargoForm.unit}
              onChange={(e) => setCargoForm(prev => ({ ...prev, unit: e.target.value }))}
              placeholder="请输入计量单位"
              required
            />
          </div>
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              onClick={() => {
                setShowCreateModal(false);
                resetForm();
              }}
              disabled={createLoading}
            >
              取消
            </Button>
            <Button
              onClick={handleCreateCargo}
              loading={createLoading}
            >
              创建货物
            </Button>
          </div>
        </div>
      </Modal>

      {/* 编辑货物模态框 */}
      <Modal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false);
          setEditingCargo(null);
          resetForm();
        }}
        title="编辑货物"
        size="md"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              货物名称 <span className="text-error-500">*</span>
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={cargoForm.name}
              onChange={(e) => setCargoForm(prev => ({ ...prev, name: e.target.value }))}
              placeholder="请输入货物名称"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              规格
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={cargoForm.specification}
              onChange={(e) => setCargoForm(prev => ({ ...prev, specification: e.target.value }))}
              placeholder="请输入规格"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              计量单位 <span className="text-error-500">*</span>
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={cargoForm.unit}
              onChange={(e) => setCargoForm(prev => ({ ...prev, unit: e.target.value }))}
              placeholder="请输入计量单位"
              required
            />
          </div>
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              onClick={() => {
                setShowEditModal(false);
                setEditingCargo(null);
                resetForm();
              }}
              disabled={editLoading}
            >
              取消
            </Button>
            <Button
              onClick={handleSaveEdit}
              loading={editLoading}
            >
              保存修改
            </Button>
          </div>
        </div>
      </Modal>

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={showDeleteDialog}
        onClose={() => {
          setShowDeleteDialog(false);
          setDeletingCargo(null);
        }}
        onConfirm={confirmDelete}
        title="删除货物"
        message={`确定要删除货物 "${deletingCargo?.name}" 吗？此操作不可撤销。`}
        confirmText="确认删除"
        cancelText="取消"
        type="danger"
        loading={deleteLoading}
      />
    </div>
  );
};